<template>
  <div class="user-container">
    <div style="text-align: start">
      <a-input
        v-model="parames.roleName"
        placeholder="请输入科室名称"
        @change="inputChange"
        style="width: 180px; margin-left: 10px"
      />
      <a-month-picker
        :show-time="{ format: 'YYYY-MM' }"
        v-model="parames.formsTime"
        placeholder="请选择填报日期"
        @change="formsTimeChange"
        style="margin-left: 10px"
      />
      <a-button v-auth="'expense:add'" @click="add" style="margin-left: 10px"
        >新建报表</a-button
      >
      <a-button
        v-auth="'expense:export'"
        @click="exportBankTable"
        style="margin-left: 10px"
        >导出银行报表</a-button
      >
    </div>
    <a-table
      :loading="loading"
      :columns="columns"
      :data-source="dataSource"
      rowKey="id"
      :pagination="false"
      style="height: 700px; margin-top: 20px; overflow: hidden"
    >
      <div slot="action" slot-scope="text, record">
        <a
          v-auth="'expense:update'"
          @click="edit(record)"
          style="margin-right: 8px"
        >
          编辑
        </a>
        <a-divider type="vertical" v-auth="'expense:update'" />
        <a @click="detail(record)" style="margin-right: 8px">
          {{ userId == 'admin' ? '查看详情' : '数据填报' }}
        </a>
        <a-divider type="vertical" />
        <a-popconfirm
          title="确定删除吗?"
          @confirm="deleteApproval(record)"
          ok-text="删除"
          cancel-text="取消"
        >
          <a style="margin-right: 8px"> 删除 </a>
        </a-popconfirm>
        <!-- <a-divider type="vertical" />
        <a
          v-auth="'expense:outautid'"
          @click="financeVerify(record)"
          style="margin-right: 8px"
        >
          财务审核
        </a>
        <a-divider type="vertical" />
        <a
          v-auth="'expense:inautid'"
          @click="directorVerify(record)"
          style="margin-right: 8px"
        >
          科室主任审核
        </a> -->
      </div>
    </a-table>
    <div class="pagination">
      <a-pagination
        :defaultPageSize="pagination.pageSize"
        :current="pagination.current"
        show-quick-jumper
        :total="pagination.total"
        show-less-items
        @change="onPageChange"
      />
    </div>
    <a-modal
      :confirm-loading="confirmLoading"
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      @ok="handleOk"
      @cancel="handleCancel"
      :width="800"
    >
      <a-form :form="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="报表名头">
          <a-input
            placeholder="请输入报表名头"
            v-decorator="[
              'reputation',
              {
                rules: [{ required: true, message: '请输入报表名头!' }],
                initialValue: form.reputation,
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="填报日期">
          <a-month-picker
            style="width: 100%"
            v-decorator="[
              'formsTime',
              {
                rules: [{ required: true, message: '请选择填报日期!' }],
                initialValue: form.formsTime,
              },
            ]"
            placeholder="请选择填报日期"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- <a-modal
      title="财务审核"
      :visible="financeVerifyVisible"
      :destroyOnClose="true"
      @ok="financeVerifyHandleOk"
      @cancel="financeVerifyHandleCancel"
      :width="800"
    >
      <a-form
        :form="financeVerifyForm"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="审批结果">
          <a-radio-group
            v-decorator="[
              'financeResult',
              {
                rules: [{ required: true, message: '请选择审批结果!' }],
                initialValue: '通过',
              },
            ]"
          >
            <a-radio value="通过">通过</a-radio>
            <a-radio value="不通过">不通过</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="审批反馈">
          <a-input
            placeholder="审批反馈"
            v-decorator="[
              'financeFeedback',
              {
                initialValue: financeVerifyForm.financeFeedback,
              },
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      title="科室审核"
      :visible="directorVerifyVisible"
      :destroyOnClose="true"
      @ok="directorVerifyHandleOk"
      @cancel="directorVerifyHandleCancel"
      :width="800"
    >
      <a-form
        :form="directorVerifyForm"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="审批结果">
          <a-radio-group
            v-decorator="[
              'directorResult',
              {
                rules: [{ required: true, message: '请选择审批结果!' }],
                initialValue: '通过',
              },
            ]"
          >
            <a-radio value="通过">通过</a-radio>
            <a-radio value="不通过">不通过</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="审批反馈">
          <a-input
            placeholder="审批反馈"
            v-decorator="[
              'directorFeedback',
              {
                initialValue: directorVerifyForm.directorFeedback,
              },
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal> -->
  </div>
</template>

<script>
import moment from 'moment';
import Cookies from 'js-cookie';
import {
  getApproval,
  addApproval,
  editApproval,
  deleteApproval,
  expertBankDerive,
  financeUpdate,
  directorUpdate,
} from '@/api/report';
import { Input } from 'ant-design-vue';
const columns = [
  {
    title: '报表名头',
    dataIndex: 'reputation',
    align: 'center',
  },
  {
    title: '填报月份',
    dataIndex: 'formsTime',
    align: 'center',
    customRender: (text) => {
      return moment(text).format('YYYY-MM');
    },
  },
  {
    title: '科室审核',
    dataIndex: 'directorResult',
    align: 'center',
  },
  {
    title: '科室审核反馈',
    dataIndex: 'directorFeedback',
    align: 'center',
  },
  {
    title: '财务审核反馈',
    dataIndex: 'financeFeedback',
    align: 'center',
  },
  {
    title: '财务审核',
    dataIndex: 'financeResult',
    align: 'center',
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
    align: 'center',
  },
];
export default {
  name: 'user',
  components: {},
  data() {
    return {
      form: this.$form.createForm(this, {
        reputation: undefined,
        formsTime: undefined,
      }),
      // financeVerifyForm: this.$form.createForm(this, {
      //   financeResult: undefined,
      //   financeFeedback: undefined,
      // }),
      // directorVerifyForm: this.$form.createForm(this, {
      //   directorResult: undefined,
      //   directorFeedback: undefined,
      // }),
      loading: true,
      dataSource: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      parames: {
        formsTime: undefined,
        roleName: undefined,
      },
      columns,
      title: '新建报表',
      visible: false,
      editId: '',
      confirmLoading: false,
      type: 'add',
      userId: JSON.parse(Cookies.get('loginInfo'))
        ? JSON.parse(Cookies.get('loginInfo')).userId
        : '',
      // financeVerifyVisible: false,
      // directorVerifyVisible: false,
    };
  },
  created() {
    this.getData();
  },
  computed: {},
  methods: {
    getData() {
      this.loading = true;
      let request = { ...this.parames };
      console.log(request);
      request.formsTime = this.parames.formsTime
        ? this.parames.formsTime.format('YYYY-MM')
        : '';
      request.currentPage = this.pagination.current;
      request.pageSize = this.pagination.pageSize;
      getApproval(request).then((response) => {
        this.dataSource = response.data.list;
        this.pagination.total = response.data.count;
        this.loading = false;
      });
    },
    onPageChange(page, pageSize) {
      this.pagination.current = page;
      this.pagination.pageSize = pageSize;
      this.getData();
    },
    edit(record) {
      console.log(record);
      this.type = 'edit';
      this.title = '编辑用户';
      this.editId = record.id;
      this.form.reputation = record.reputation;
      this.form.formsTime = moment(record.formsTime, 'YYYY-MM');
      this.visible = true;
    },
    add() {
      this.type = 'add';
      this.title = '新建用户';
      this.visible = true;
    },
    handleCancel() {
      this.initForm();
      this.visible = false;
    },
    handleOk(e) {
      e.preventDefault();
      const { type } = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          let request = { ...values, id: this.editId };
          request.formsTime = values.formsTime.format('YYYY-MM');
          console.log(request);
          if (type === 'add') {
            addApproval(request).then((response) => {
              console.log(response);
              if (response.code == 200) {
                this.$message.success(response.message);
                this.getData();
                this.visible = false;
              } else {
                this.$message.error(response.message);
              }
              this.confirmLoading = false;
              this.initForm();
            });
          } else {
            editApproval(request).then((response) => {
              console.log(response);
              if (response.code == 200) {
                this.$message.success(response.message);
                this.getData();
                this.visible = false;
              } else {
                this.$message.error(response.message);
              }
              this.confirmLoading = false;
              this.initForm();
            });
          }
        }
      });
    },
    initForm() {
      Object.keys(this.form.getFieldsValue()).forEach((key) => {
        this.form[key] = undefined;
      });
    },
    deleteApproval(record) {
      deleteApproval([record.id]).then((response) => {
        if (response.code == 200) {
          this.getData();
          this.$message.success('删除成功');
        } else {
          this.$message.error(response.message);
        }
      });
    },
    detail(record) {
      console.log(record);
      this.$router.push({
        path: '/report-create',
        query: {
          id: record.id,
          directorResult: record.directorResult,
          financeResult: record.financeResult,
        },
      });
    },
    // financeVerify(record) {
    //   console.log(record);
    //   this.editId = record.id;
    //   this.financeVerifyVisible = true;
    // },
    // financeVerifyHandleOk(e) {
    //   e.preventDefault();
    //   this.financeVerifyForm.validateFields((err, values) => {
    //     if (!err) {
    //       let request = { ...values, id: this.editId };
    //       financeUpdate(request).then((response) => {
    //         console.log(response);
    //         if (response.code == 200) {
    //           this.$message.success(response.message);
    //           this.getData();
    //           this.financeVerifyVisible = false;
    //         } else {
    //           this.$message.error(response.message);
    //         }
    //       });
    //     }
    //   });
    // },
    // financeVerifyHandleCancel() {
    //   this.financeVerifyVisible = false;
    // },
    // directorVerify(record) {
    //   this.editId = record.id;
    //   this.directorVerifyVisible = true;
    // },
    // directorVerifyHandleOk(e) {
    //   e.preventDefault();
    //   this.directorVerifyForm.validateFields((err, values) => {
    //     if (!err) {
    //       let request = { ...values, id: this.editId };
    //       directorUpdate(request).then((response) => {
    //         console.log(response);
    //         if (response.code == 200) {
    //           this.$message.success(response.message);
    //           this.getData();
    //           this.directorVerifyVisible = false;
    //         } else {
    //           this.$message.error(response.message);
    //         }
    //       });
    //     }
    //   });
    // },
    // directorVerifyHandleCancel() {
    //   this.directorVerifyVisible = false;
    // },
    formsTimeChange(date, dateString) {
      console.log(date);
      console.log(dateString);
      if (dateString) {
        this.parames.formsTime = moment(dateString, 'YYYY-MM');
      } else {
        this.parames.formsTime = '';
      }
      this.getData();
    },
    inputChange(e) {
      this.parames.roleName = e.target.value;
      this.getData();
    },
    exportBankTable() {
      const { formsTime } = this.parames;
      if (!formsTime) {
        this.$message.info('请先筛选日期，才能导出银行报表');
      } else {
        console.log(formsTime);
        let formsTimes = formsTime.format('YYYY-MM');
        console.log(formsTimes);
        expertBankDerive({ formsTime: formsTimes }).then((response) => {
          const blob = new Blob([response]);
          const url = URL.createObjectURL(blob);
          const link = document.createElement('a');
          const timestamp = new Date()
            .toISOString()
            .replace(/[-T:]/g, '')
            .slice(0, 14);
          const fileName = `${timestamp}.xlsx`;
          link.href = url;
          link.download = fileName;
          link.click();
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.user-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .pagination {
    height: 30px;
    line-height: 30px;
    width: 100%;
    text-align: right;
  }
}
</style>
